﻿using LD.Tool;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using 右下角弹窗.DiagShow;

namespace LD.Host
{
    public partial class FrmFlow : BaseFrm
    {
        public FrmFlow()
        {
            InitializeComponent();
            this.Shown += FrmFlow_Shown;
        }

        private void FrmFlow_Shown(object sender, EventArgs e)
        {
            base.Permission(UserType.管理员);

            if (this.IsDisposed)
                return;

            this.FormClosed += FrmFlow_FormClosed;
            Appbus.PartNo.PartNoChange += PartNo_PartNoChange;

            LoadTool();
            LoadFlow();
        }

        private void PartNo_PartNoChange(TB_PartNo partNo)
        {
            MRefresh();
        }

        private void FrmFlow_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private void tsb_add_Click(object sender, EventArgs e)
        {
            FrmFlowEdit edit = new FrmFlowEdit();
            if (edit.ShowDialog() == DialogResult.OK)
            {
                Appbus.PartNo.Config.Flow.Add(edit.Flow);
                TabPage tabPage = GetTabPage(edit.Flow);
                tabPage.Tag = edit.Flow;
                tabControl1.TabPages.Add(tabPage);
                tabControl1.SelectedTab = tabPage;
            }
        }

        private void tsb_delete_Click(object sender, EventArgs e)
        {
            var selectTab = this.tabControl1.SelectedTab;
            if (selectTab != null)
            {
                if (MessageBox.Show($"你确定要删除【{selectTab.Text}】页签", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    this.tabControl1.TabPages.Remove(selectTab);
                    TB_Flow removeFlow = Appbus.PartNo.Config.Flow.Where(p => p.Name == selectTab.Name).FirstOrDefault();
                    Appbus.PartNo.Config.Flow.Remove(removeFlow);
                }
            }
        }

        private void LoadTool()
        {
            treeViewY1.Nodes.Clear();
            ToolBox toolBox = new ToolBox();
            var list = toolBox.GetList();
            if (!(bool)Cache.GetCache(CONST.BC))
                list.Remove(ToolEnum.BC.ToString());
            if (!(bool)Cache.GetCache(CONST.VISION))
                list.Remove(ToolEnum.Vision.ToString());
            if (!(bool)Cache.GetCache(CONST.MES))
                list.Remove(ToolEnum.Mes.ToString());

            foreach (var item in list)
            {
                TreeNode treeNode = new TreeNode();
                treeNode.Text = item.Key;
                treeNode.ImageIndex = 1;
                treeNode.SelectedImageIndex = 2;
                foreach (var child in item.Value)
                {
                    TreeNode tn1 = new TreeNode();
                    tn1.Text = child.Text;
                    tn1.Tag = child;
                    tn1.Name = child.ClassName;
                    tn1.ImageIndex = 3;
                    tn1.SelectedImageIndex = 2;
                    treeNode.Nodes.Add(tn1);
                }
                this.treeViewY1.Nodes.Add(treeNode);
            }
        }
        private void LoadFlow()
        {
            this.tabControl1.TabPages.Clear();
            if (Appbus.PartNo.Config == null)
                return;
            foreach (var item in Appbus.PartNo.Config.Flow)
            {
                var page = GetTabPage(item);
                this.tabControl1.TabPages.Add(page);
            }
        }
        private TabPage GetTabPage(TB_Flow flow)
        {
            TabPage tabPage = new TabPage();
            tabPage.Name = flow.Name;
            tabPage.ToolTipText = flow.FlowType == 0 ? "任务" : "流程";
            tabPage.Text = flow.Name;
            tabPage.Tag = flow;
            tabPage.ContextMenuStrip = this.contextMenuStrip1;
            ToolItemCollection tools = new ToolItemCollection();
            tools.Name = "tools";
            tools.Tools = flow.Tools;
            tools.Dock = DockStyle.Fill;
            tools.BorderStyle = BorderStyle.FixedSingle;
            tabPage.BackColor = Color.White;

            tabPage.Controls.Add(tools);
            if (flow.FlowType == 1)
                TabPageSetColor(tabPage);

            return tabPage;
        }
        public void Save()
        {
            Dialog dialog = new Dialog();
            List<TB_Flow> flows = new List<TB_Flow>();
            foreach (TabPage item in this.tabControl1.TabPages)
            {
                var flow = item.Tag as TB_Flow;
                flow.Tools.Clear();
                var toolCollection = item.Controls.Find("tools", true);
                if (toolCollection.Length > 0)
                {
                    var toolControl = (ToolItemCollection)toolCollection[0];
                    int sort = 1;
                    toolControl.ToolCollectFormat();
                    foreach (var toolItem in toolControl.ToolItems)
                    {
                        var tool = toolItem.Tool;
                        tool.Sort = sort;
                        flow.Tools.Add(tool);
                        sort++;
                    }
                }
                flows.Add(flow);
            }

            Appbus.PartNo.Config.Flow = flows;
            Appbus.PartNo.Save();
            dialog.Success("保存成功");
        }
        /// <summary>
        /// 刷新
        /// </summary>
        public void MRefresh()
        {
            //控件更新
            LoadTool();
            LoadFlow();
        }

        private void treeViewY1_ItemDrag(object sender, ItemDragEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.treeViewY1.SelectedNode = e.Item as TreeNode;
                if ((e.Item as TreeNode).Tag != null)
                {
                    TB_Tool tool = (e.Item as TreeNode).Tag as TB_Tool;
                    Console.WriteLine(tool.Name);
                    this.DoDragDrop(tool, DragDropEffects.Move);
                }
            }
        }
        private void tsb_run_Click(object sender, EventArgs e)
        {
            TabPage tabPage = this.tabControl1.SelectedTab;
            foreach (Control item in tabPage.Controls[0].Controls)
            {
                if (item.GetType() == typeof(ToolItem))
                {
                    ToolItem _item = (ToolItem)item;
                    if (_item.IsEnabled)
                    {
                        var opResult = _item.Execute();
                        if (!opResult.IsSuccess)
                            return;
                    }
                }
            }
        }
        private void TabPageSetColor(TabPage page)
        {
            page.BorderStyle = BorderStyle.FixedSingle;
            //using (Brush br = new SolidBrush(Color.Blue))
            //{
            //    var g = page.CreateGraphics();
            //    g.FillRectangle(br, page.Bounds);
            //    g.DrawString("aaa", page.Font, Brushes.Red, 0, 0);
            //    Rectangle rect = page.Bounds;
            //    g.DrawRectangle(Pens.Red, rect);

            //    page.Invalidate();
            //}
            //tabControl1.Invalidate();
        }

        public void StateChange(StateEnum state)
        {
            if (state == StateEnum.自动模式)
            {
                toolStrip1.Enabled = false;
                this.tabControl1.Enabled = false;
            }
            else
            {
                toolStrip1.Enabled = true;
                this.tabControl1.Enabled = true;
            }
        }

        private void 属性ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TabPage tabPage = (TabPage)((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl;
            if (tabPage != null)
            {
                FrmFlowEdit edit = new FrmFlowEdit(tabPage.Text);
                if (edit.ShowDialog() == DialogResult.OK)
                {

                }
            }
        }

        private void 粘贴工具ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var tabPage = (TabPage)((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl;
            var childControl = tabPage.Controls.Find("tools", false);
            if (childControl != null && childControl.Count() > 0)
            {
                var toolControl = (ToolItemCollection)childControl[0];
                var dataString = Clipboard.GetData("ld") ?? "";
                var tool = Newtonsoft.Json.JsonConvert.DeserializeObject<TB_Tool>(dataString.ToString());
                tool.FlowName = tabPage.Text;
                toolControl.AddTool(tool);
            }
        }
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var tabPage = (TabPage)((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl;
            var childControl = tabPage.Controls.Find("tools", false);
            if (childControl != null && childControl.Count() > 0)
            {
                var toolControl = (ToolItemCollection)childControl[0];
                var dataString = Clipboard.GetData("lds") ?? "";
                var tools = Newtonsoft.Json.JsonConvert.DeserializeObject<List<TB_Tool>>(dataString.ToString());
                foreach (var item in tools)
                {
                    item.FlowName = tabPage.Text;
                    toolControl.AddTool(item);
                }
            }
        }

        private void 复制toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            var tabPage = (TabPage)((sender as ToolStripMenuItem).GetCurrentParent() as ContextMenuStrip).SourceControl;
            var childControl = tabPage.Controls.Find("tools", false);
            if (childControl != null && childControl.Count() > 0)
            {
                var toolControl = (ToolItemCollection)childControl[0];
                Clipboard.SetData("lds", Newtonsoft.Json.JsonConvert.SerializeObject(toolControl.Tools));
            }
        }
    }
}
